package com.juc.completableFuture;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class CompletableFutureDemo3 {
	static List<NetMall>  list = Arrays.asList(
			new NetMall("jd"),
			new NetMall("pdd"),
			new NetMall("tmall")
		);
	
	public static List<String> getPriceByStep(List<NetMall> list,String productName){
		return list.stream().map(m->String.format(productName + "  in %s price is %.2f", m.getMallName(),m.calcPrice(productName))).collect(Collectors.toList());
	}
	
	public static List<String> getPriceByAsyn(List<NetMall> list,String productName) {
		return list.stream().map(m-> 
		         CompletableFuture.supplyAsync(()->String.format(productName + "  in %s price is %.2f", m.getMallName(),m.calcPrice(productName))))
				.collect(Collectors.toList())
				.stream()
				.map(CompletableFuture::join)
				.collect(Collectors.toList());
	}
	
	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		List<String> lists = getPriceByStep(list,"mysql");
		for (String string : lists) {
			System.out.println(string);
		}
		long end =  System.currentTimeMillis();
		System.out.println("-----costTime " + (end - start) + "毫秒");
		
		long start1 = System.currentTimeMillis();
		List<String> lists1 = getPriceByAsyn(list,"mysql");
		for (String string : lists1) {
			System.out.println(string);
		}
		long end1 =  System.currentTimeMillis();
		System.out.println("-----costTime " + (end1 - start1) + "毫秒");
	}
}

class NetMall{
	private String mallName;

	public String getMallName() {
		return mallName;
	}
	NetMall(String mallName) {
		this.mallName = mallName;
	}
	public void setMallName(String mallName) {
		this.mallName = mallName;
	}
	
	public double calcPrice(String productName) {
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
	}
}
